﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using LearnNet.BLL;
using System.Xml;
using LearnNet.Common;
using System.Drawing;
using System.Reflection;
using Advertise;
using System.Threading;
using System.Collections;
using mshtml;
namespace Advertise
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        protected RegistEntity regEntity = new RegistEntity();
        private XmlHelper xmlHelper = new XmlHelper(string.Concat(Application.StartupPath, "/config.xml"));
        private Thread threadOne;
        private DataTable dt = new DataTable();
        private ReportContent regContent = new ReportContent();
        private int state = 0;
        public System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
        /// <summary>
        /// 执行列表
        /// </summary>
        protected  UpdateInfo updateInfo = null;
        /// <summary>
        /// 注册信息列表
        /// </summary>
        protected List<RegistEntity> regeistEntitys = null;
        //private delegate void ShowTask(UpdateInfo upInfo);
        //private delegate void ThreadAbort(object sender, EventArgs e);



        private void Form2_Load(object sender, EventArgs e)
        {
            // Control.CheckForIllegalCrossThreadCalls = false;
            this.webBrowser1.Navigating += new WebBrowserNavigatingEventHandler(webBrowser1_Navigating);
            this.webBrowser1.Navigated += new WebBrowserNavigatedEventHandler(webBrowser1_Navigated);
            this.webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
            this.webBrowser1.NewWindow += new CancelEventHandler(webBrowser1_NewWindow);
        
            timer.Tick += new EventHandler(timer_Tick);
            timer.Interval = 2000;
            timer.Enabled = false;
            BindList();

            
        }
        private void BindList()
        {
            regeistEntitys = new List<RegistEntity>();
            RegistEntity reg = new RegistEntity();
            reg.Name = "shang287350508";//shang345413525 qwe231231
            reg.Pwd = "qwe231231"; //	114	shang287350508	Ifeng	qwe231231	
            reg.Type = "Ifeng";
            regeistEntitys.Add(reg);
            //reg = new RegistEntity();
            //reg.Name = "yang0000meng";
            //reg.Pwd = "yang__2266452";
            //reg.Type = "Sina";
            
            //regeistEntitys.Add(reg);
 
            //DataTable dt = new DataTable();
            //dt = LearnNet.DAL.DALHelper.LearnNetHelper.ExecuteQuery(CommandType.Text, "select * from userinfo", null);
            //if (dt == null)
            //{
            //    MessageBox.Show("请先注册");
            //    return;
            //}
            //for (int i = 0; i < dt.Rows.Count; i++)
            //{
            //    reg = new RegistEntity();
            //    reg.Name = dt.Rows[i]["name"].ToString();
            //    reg.Pwd = dt.Rows[i]["pwd"].ToString();
            //    reg.Type = dt.Rows[i]["website"].ToString();
            //    reg.Num = i;
            //    regeistEntitys.Add(reg);
            //}
         
            updateInfo = new UpdateInfo();
            updateInfo.Count = regeistEntitys.Count-1;
            updateInfo.Index = -1;
            label1.Text = "共有" + regeistEntitys.Count.ToString() + "个";
           
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            if (tbTitile.Text == "")
            {
                MessageBox.Show("请填写标题");
                return;
            }
            if (tbContent.Text == "")
            {
                MessageBox.Show("请填写内容");
                return;
            }
            regContent.Title = tbTitile.Text;
            regContent.Content = tbContent.Text;
            regContent.ClassType = "1";
            //ThreadDemo();
            //Start();
            state = 0;
            updateInfo.Index = -1;
            btnSend.Enabled = false;
            this.webBrowser1.Navigate("about:blank");
        }

        public  void timer_Tick(object sender, EventArgs e)
        {
          
                this.webBrowser1.Document.Click += new HtmlElementEventHandler(Document_Click);

                string str = string.Empty;
                //UpdateInfo upInfo = new UpdateInfo();
                //upInfo.Count = dt.Rows.Count;
                //upInfo.Index = 0;
                string strSql = string.Empty;
                if (state == 0)
                {
                    updateInfo.Index++;
                    if (updateInfo.Index > updateInfo.Count)
                    {
                        btnSend.Enabled = true;
                        timer.Enabled = false;
                    
                      //  this.webBrowser1.Navigate("about:blank");
                        return;
                    }
                   
                }

                IRepost irepost = GetRepost(regeistEntitys[updateInfo.Index].Type) as IRepost;
                string strMessage = string.Empty;

                Point p = new Point(100, 260);
                webBrowser1.Document.Window.ScrollTo(p);
                switch (state)
                {
                    case 0:
                        {
                           
                            webBrowser1.Url = new Uri(xmlHelper.GetAttribute("root/station[@code='" + regeistEntitys[updateInfo.Index].Type + "']/logout", "url").Replace("$0", regeistEntitys[updateInfo.Index].Name));
                            state = 1;
                            break;
                        }

                    case 1:
                        {
                            webBrowser1.Url = new Uri(xmlHelper.GetAttribute("root/station[@code='" + regeistEntitys[updateInfo.Index].Type + "']/login", "url"));
                            state = 2;
                            break;
                        }
                    case 2:
                        {
                            strMessage = irepost.LoginIn(webBrowser1, regeistEntitys[updateInfo.Index]);
                            if (strMessage != "")
                                MessageBox.Show(strMessage);
                            //   ReportHelper.HerfClick(webBrowser1, ");
                            state = 3;
                            timer.Interval = 3000;
                            break;
                        }

                    case 3:
                        {
                            webBrowser1.Url = new Uri(xmlHelper.GetAttribute("root/station[@code='" + regeistEntitys[updateInfo.Index].Type + "']/report", "url").Replace("$0", regeistEntitys[updateInfo.Index].Name));
                            state = 4;
                            timer.Enabled = false;
                            break;
                        }
                    case 4:
                        {
                            p = new Point(100, 760);
                            webBrowser1.Document.Window.ScrollTo(p);
                            strMessage = irepost.Report(webBrowser1, regContent);
                            if (strMessage != "")
                                MessageBox.Show(strMessage);
                            state = 0;
                            timer.Interval = 3000;
                            break;
                        }
                    case 5:
                        {
                            timer.Interval = 2000;
                            webBrowser1.Url = new Uri(xmlHelper.GetAttribute("root/station[@code='" + regeistEntitys[updateInfo.Index].Type + "']/login", "url"));
                            state = 0;
                            timer.Enabled = false;
                            break;
                        }
                   
                    default:{
                              timer.Enabled = false;
                            break;
                        }

                }
              
               
            
        }

       

        protected void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (e.Url.ToString() != webBrowser1.Url.ToString())
                return;
            if (webBrowser1.ReadyState.ToString() == WebBrowserReadyState.Complete.ToString())
            {

                this.webBrowser1.Document.Window.Error += new HtmlElementErrorEventHandler(Window_Error);

                if (updateInfo.Index > updateInfo.Count)
                {
                    timer.Enabled = false;
                    btnSend.Enabled = true;
                }
                else
                {
                    timer.Enabled = true;
                    
                }
            
             

                //  MessageBox.Show(webBrowser1.ReadyState.ToString());

                // 在WebBrowser的DocumentComplete中写下面的代码。 
                //触发事件
                //IHTMLDocument2 m_pHtmlDoc2 = (IHTMLDocument2)hd.DomDocument;
                //HTMLDocumentEvents2_Event iEvent = (HTMLDocumentEvents2_Event)m_pHtmlDoc2;
                //iEvent.onclick += new HTMLDocumentEvents2_onclickEventHandler(iEvent_onclick);
                //iEvent.oncontextmenu += new HTMLDocumentEvents2_oncontextmenuEventHandler(ContextMenuEventHandler);
                //MessageBox.Show(webBrowser1.ReadyState.ToString() + "DocumentCompleted");


            }
        }
        protected Dictionary<string, object> RepostList = new Dictionary<string, object>();

        protected object GetRepost(string type)
        {
            string typeName = string.Concat("Advertise.Repost", type);
            if (!RepostList.ContainsKey(type))
            {
                Assembly asm = Assembly.GetExecutingAssembly();

                object[] parameters = new object[2];
                parameters[0] = webBrowser1;
                parameters[1] = xmlHelper;
                Object obj = asm.CreateInstance(typeName, true, BindingFlags.Default, null, parameters, null, null);
                RepostList.Add(type, obj);
            }
            return RepostList[type];
           
        }

        #region 监听webBrowser事件
        void Document_Click(object sender, HtmlElementEventArgs e)
        {
            MessageBox.Show(e.EventType);
            MessageBox.Show(e.FromElement.Id + e.FromElement.InnerHtml);

        }

        void webBrowser1_NewWindow(object sender, CancelEventArgs e)
        {
            //e.Cancel = true;
        }

        protected void Window_Error(object sender, HtmlElementErrorEventArgs e)
        {
            e.Handled = true;
        }

        public bool iEvent_onclick(IHTMLEventObj pEvtObj)
        {
            MessageBox.Show(pEvtObj.qualifier);
            return true;
        }
        // 事件处理函数,目的，不使用WebBrowser自己的菜单。 
        private bool ContextMenuEventHandler(IHTMLEventObj e)
        {
            MessageBox.Show("ContextMenuEventHanderl");
            return false;
        }

       
        protected void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            HtmlDocument hd = webBrowser1.Document;
            IHTMLWindow2 win = (IHTMLWindow2)hd.Window.DomWindow;
            string s = @"function confirm() {";
            s += @"return true;";
            s += @"}";
            s = @"function killerrors() { return true; } window.onerror = killerrors; ";

            s += @"function alert() {}";
            s += @"window.onbeforeunload = function(){};$('vForm').onsubmit=function(){} ";
            win.execScript(s, "javascript");
               
            
            //禁用js弹出窗
            //HtmlDocument hd = webBrowser1.Document;
            //    IHTMLWindow2 win = (IHTMLWindow2)hd.Window.DomWindow;
            //    string s = @"function confirm() {";
            //    s += @"return true;";
            //    s += @"}";
            //    s = @"function killerrors() { return true; } window.onerror = killerrors; ";
            //    s += @"function alert() {}";
            //    s += @"window.onbeforeunload = function(){}; ";
            //    win.execScript(s, "javascript");
            
        }
        protected void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
        {
            //MessageBox.Show(webBrowser1.ReadyState.ToString());
        }
        #endregion

        private void btnRequest_Click(object sender, EventArgs e)
        {

        }

        private void btnReg_Click(object sender, EventArgs e)
        {
            FrmReg fm = new FrmReg();
            fm.Show();
        }


      


    }

}
